var totalPage = 1;
$(document).ready(function () {
    initSize();
    Judgeidentity();
    var layer = layui.layer,
        form = layui.form;

    $("#header-date").html(new Date().getFullYear() + '年' + (new Date().getMonth() + 1) + '月' + new Date().getDate() + '日');
    $("#header-week").html("星期" + "日一二三四五六".charAt(new Date().getDay()));
    $("#orgname>span").html(localStorage.getItem('username'));
    /*选择机房*/
    $('#header-room').click(function () {
        $('.room-choose').toggle();
    })
    /*进入首页*/
    $('#header-menu').click(function (e) {
        window.location.href = 'index.html';
    })
    /*进入后台管理*/
    $('#manage').click(function () {
        window.location.href = "orgmanage.html";
    })
    /*后台管理菜单点击*/
    $('.nav-item').click(function () {
        $(this).addClass('active').siblings().removeClass("active");
        if (this.id != '') {
            window.location.href = this.id + '.html';
        }

    })
    $.each($(".nav-item"), function (index, el) {
        if (window.location.href.indexOf(el.id) > -1) {
            $('#' + el.id).addClass('active');
        }

    });
    /*注销*/
    $('#logout').click(function () {
        logout();
    })

    initRooms();
})

/*初始化默认字体大小*/
function initSize() {
    //适应不同分辨率
    let fontSize;
    resize();
    window.onresize = resize;

    function resize() {
        let winW = window.innerWidth;
        if (winW >= 1440) { fontSize = winW / 1440 * 100 }
        document.getElementsByTagName('html')[0].style.cssText = "font-size:" + fontSize + "px";
    }
}

///数组排序
function getMaxSort(arr) {
    var max
    for (var i = 0; i < arr.length; i++) {
        for (var j = i; j < arr.length; j++) {
            if (arr[i] < arr[j]) {
                max = arr[j]
                arr[j] = arr[i]
                arr[i] = max
            }
        }
    }
    return arr
}

///图片自动旋转
function rotatepic(id) {
    //图片旋转
    var img = $("#" + id);
    var speed = 30;
    var deg = 0;
    setInterval(function () {
        img.css({
            '-ms-transform': 'rotate(' + deg + 'deg)',
            /* IE 9 */
            '-moz-transform': 'rotate(' + deg + 'deg)',
            /* Firefox */
            '-webkit-transform': 'rotate(' + deg + 'deg)',
            /* Safari and Chrome */
            '-o-transform': 'rotate(' + deg + 'deg)',
            /* Opera */
            'transform': 'rotate(' + deg + 'deg)'
        });
        deg += 1;
        if (deg >= 360) {
            deg = 0;
        }
    }, speed);

}

/*图片循环*/
$.fn.scrollLoop = function (options) {

    var def = $.extend({
        'time': 5000,
        'offsetX': -50,
        'deltaX': 50,
        'offsetY': 0,
        'deltaY': 0,
        'position_type': 'absolute',
        'play_count': -1
    }, options);

    if (def['play_count'] == 0)
        return this;
    else
        def['play_count']--;

    return this.css({ position: def['position_type'], left: def['offsetX'], top: def['offsetY'] }).animate({ left: def['deltaX'], top: def['deltaY'] }, def['time'], function () { $(this).scrollLoop({ 'time': def['time'], 'offsetX': def['offsetX'], 'deltaX': def['deltaX'], 'offsetY': def['offsetY'], 'deltaY': def['deltaY'], 'position_type': def['position_type'], 'play_count': def['play_count'] }); });
}

/*判断字段是否为空或者*/
function checkNullOrEmpty(field) {

    if (field == null || field === "") {
        return ''
    } else {
        return field
    }

}

/**/


/*字符长度过长处理*/
function exceedingLengthHandle(str, length) {
    if (str == null) {
        str = ''
    }
    return (str.length < length) ? str : (str.substring(0, length) + '...')

}

function logout() {
    layer.confirm('确定退出系统？', {
        btn: ['确定', '取消'] //按钮
    }, function () {
        loginOut();
    });
}

function loginOut() {
    $.ajax({
        url: ajaxPrefix() + '/logout',
        type: "post",
        contentType: "application/json",
        success: function (result) {
            localStorage.setItem('sessionId', "");
            localStorage.setItem('username', '');
            window.location.href = "login.html";
        },
        error: function (result) {
            localStorage.setItem('sessionId', "");
            localStorage.setItem('username', '');
            window.location.href = "login.html";
        }
    })
}

function Judgeidentity() {
    var sessionId = localStorage.getItem('sessionId');
    if (sessionId == null || sessionId == "") {
        window.location.href = "login.html";
    }
}

function ajaxPrefix() {
    return '/rest/icr'
}

function Ajax(url, callBack, parms, type) {
    $.ajax({
        url: ajaxPrefix() + url,
        type: type ? type : 'get',
        data: parms ? parms : '',
        contentType: "application/json",
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader("SessionId", localStorage.getItem('sessionId'));
        },
        success: function (result) {
            if (result.status == 200) {
                callBack(result);
            }

        }
    });
}

//百度转高德
function bd_toGd(bd_lng, bd_lat) {
    var X_PI = Math.PI * 3000.0 / 180.0;
    var x = bd_lng - 0.0065;
    var y = bd_lat - 0.006;
    var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI);
    var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI);
    var gg_lng = z * Math.cos(theta);
    var gg_lat = z * Math.sin(theta);
    return { lng: gg_lng, lat: gg_lat }
}

var GPS = {
    PI: 3.14159265358979324,
    x_pi: 3.14159265358979324 * 3000.0 / 180.0,
    delta: function (lat, lon) {
        // Krasovsky 1940
        //
        // a = 6378245.0, 1/f = 298.3
        // b = a * (1 - f)
        // ee = (a^2 - b^2) / a^2;
        var a = 6378245.0; //  a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
        var ee = 0.00669342162296594323; //  ee: 椭球的偏心率。
        var dLat = this.transformLat(lon - 105.0, lat - 35.0);
        var dLon = this.transformLon(lon - 105.0, lat - 35.0);
        var radLat = lat / 180.0 * this.PI;
        var magic = Math.sin(radLat);
        magic = 1 - ee * magic * magic;
        var sqrtMagic = Math.sqrt(magic);
        dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * this.PI);
        dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * this.PI);
        return { 'lat': dLat, 'lon': dLon };
    },

    //GPS---高德
    gcj_encrypt: function (wgsLat, wgsLon) {
        /*        if (this.outOfChina(wgsLat, wgsLon))
                    return { 'lng': wgsLat, 'lat': wgsLon };*/

        var d = this.delta(wgsLat, wgsLon);
        return { 'lng': wgsLat + d.lat, 'lat': wgsLon + d.lon };
    },
    outOfChina: function (lat, lon) {
        if (lon < 72.004 || lon > 137.8347)
            return true;
        if (lat < 0.8293 || lat > 55.8271)
            return true;
        return false;
    },
    transformLat: function (x, y) {
        var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(y * this.PI) + 40.0 * Math.sin(y / 3.0 * this.PI)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(y / 12.0 * this.PI) + 320 * Math.sin(y * this.PI / 30.0)) * 2.0 / 3.0;
        return ret;
    },
    transformLon: function (x, y) {
        var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * this.PI) + 20.0 * Math.sin(2.0 * x * this.PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(x * this.PI) + 40.0 * Math.sin(x / 3.0 * this.PI)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(x / 12.0 * this.PI) + 300.0 * Math.sin(x / 30.0 * this.PI)) * 2.0 / 3.0;
        return ret;
    }
};



/**
 * [通过参数名获取url中的参数值]
 * 示例URL:http://htmlJsTest/getrequest.html?uid=admin&rid=1&fid=2&name=小明
 * @param  {[string]} queryName [参数名]
 * @return {[string]}           [参数值]
 */
function GetQueryValue1(queryName) {
    var reg = new RegExp("(^|&)" + queryName + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return decodeURI(r[2]);
    } else {
        return null;
    }
}

function initRooms() {
    Ajax("/index/room/list", initRoomsBack);
    function initRoomsBack(result) {
        if (result.status == 200) {
            var data = result.result;
            const t1 = data.filter((i) => i.type == 1);
            const t2 = data.filter((i) => i.type == 2);

            if (null != data && data != 'null') {
                $('.room-choose').empty().append(`<li class="nav-header">机房</li>` +
                    t1.reduce(function (x, y) {
                        return `<span style="color:${$('.selectedRoom').attr("data-id") == y.id ? '#0DF5F5' : ''}" 
                                      onclick=intoCR("${y.id}","${y.name}")>${y.name}</span>` + x;
                    }, '') + `<li class="nav-header">管井</li>` +
                    t2.reduce(function (x, y) {
                        return `<span style="color:${$('.selectedRoom').attr("data-id") == y.id ? '#0DF5F5' : ''}" 
                                      onclick=intoTW("${y.id}","${y.name}")>${y.name}</span>` + x;
                    }, ''));
            }
        }
    }
}
//进入机房
intoCR = (id, name) => {
    window.location.href = 'roominfo.html?id=' + id + '&name=' + name;
}
//进入管井
intoTW = (id, name) => {
    window.location.href = 'well.html?id=' + id + '&name=' + name;
}

function renderForm() {
    layui.use('form', function () {
        var form = layui.form;
        form.render();
    });
}


function initRoomInfo() {
    roomid = GetQueryValue1('id');
    roomName = GetQueryValue1('name');

    if (roomName.length > 6) {
        $('.selectedRoom').attr('title', roomName);
        $('.selectedRoom').css({
            'width': '0.95rem',
            'overflow': 'hidden',
            'white-space': 'nowrap',
            'text-overflow': 'ellipsis',
            'justify-content': 'flex-start',
            'text-indent': '0.05rem',
            'font-size': '0.12rem'
        });

    }

    $('.selectedRoom').attr("data-id", roomid);
    $('.selectedRoom').html(roomName);

}